package com.just.springbootmessage.rabbitmq;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 延时队列配置
 */
@Configuration
public class DelayRabbitConfig {

    /**
     * 每条消息过期时间都是2000ms
     */
    @Bean
    public Queue delayQueueTTL() {
        return QueueBuilder.durable("delay-queue")
                .withArgument("x-dead-letter-exchange", "delay-exchange")
                .withArgument("x-dead-letter-routing-key", "process-queue")
                .withArgument("x-message-ttl",2000)                       //队列的过期时间
                .build();
    }

    /**
     * 单个消息自定义过期的队列
     */
    @Bean
    public Queue delayQueueMessageTTL() {
        return QueueBuilder.durable("delay-per-message-queue")
                .withArgument("x-dead-letter-exchange", "delay-exchange")
                .withArgument("x-dead-letter-routing-key", "process-queue")
                .build();
    }

    /**
     * 正常的队列
     */
    @Bean
    public Queue delayProcessQueue() {
        return QueueBuilder.durable("process-queue")
                .build();
    }

    /**
     * 延迟消息队列的交换机
     */
    @Bean
    public DirectExchange delayExchange(){
        return new DirectExchange("delay-exchange");
    }

    /**
     * 将实际消费队列绑定到delayExchange
     */
    @Bean
    public Binding delayBinding(Queue delayProcessQueue,DirectExchange delayExchange){
        return BindingBuilder.bind(delayProcessQueue)
                .to(delayExchange)
                .with("process-queue");
    }

    /**
     * 剩下的也都绑定到这个交换机
     */
    @Bean
    public Binding delayQueueBinding(Queue delayQueueTTL,DirectExchange delayExchange){
        return BindingBuilder.bind(delayQueueTTL)
                .to(delayExchange)
                .with("delay-queue");
    }

    @Bean
    public Binding delayMessageQueueBinding(Queue delayQueueMessageTTL,DirectExchange delayExchange){
        return BindingBuilder.bind(delayQueueMessageTTL)
                .to(delayExchange)
                .with("delay-per-message-queue");
    }

    /*@Bean
    SimpleMessageListenerContainer processContainer(ConnectionFactory connectionFactory, DelayMessageReceiver processReceiver) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setQueueNames("process-queue"); // 监听delay_process_queue
        container.setMessageListener(new MessageListenerAdapter(processReceiver));
        return container;
    }*/

}
